package com.lyf.juc.learn.sggadvance.locks;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author LYF
 * @date 2022/7/2
 */
class Ticket{
    private  int num = 50;
    private Object lock0 = new Object();
    //Lock lock = new ReentrantLock();
    /*
    默认非公平锁
    public ReentrantLock() {
        sync = new NonfairSync();
    }
     */
    Lock lock = new ReentrantLock(true);
    public void sale(){
//        lock.lock();
//        try {
//            if(num>0){
//                num--;
//                System.out.println(Thread.currentThread().getName()+"::卖出一张票，剩余"+num);
//            }
//        }finally {
//            lock.unlock();
//        }

        // 非公平 “synchronized是非公平锁,没有浪费线程唤醒阶段的时间,执行新调用的方法,增加吞吐量,缺点是可能会造成饥饿锁。”
//        synchronized (lock0){
//            if(num>0){
//                num--;
//                System.out.println(Thread.currentThread().getName()+"::卖出一张票，剩余"+num);
//            }
//        }

    }
}
public class FairLockTests {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(()->{while (true)ticket.sale();},"a").start();
        new Thread(()->{while (true)ticket.sale();},"b").start();
        new Thread(()->{while (true)ticket.sale();},"c").start();
    }
}
